package com.finger.wx.assistant.util.xml;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class SimpleXmlFilter implements XmlFilter {
	private String text = null;
	// 常用的过滤正则表达式
	public final static String[] REG = { "\t", "<\\?.*?\\?>", "<!.*?>", "<%.*?%>", "\\s{2,}" };

	// 读取xml文档返回字符串
	public SimpleXmlFilter(File file) throws IOException {
		FileInputStream inStream = null;
		try {
			inStream = new FileInputStream(file);
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = inStream.read(buffer)) != -1) {
				outStream.write(buffer, 0, len);
			}
			byte[] data = outStream.toByteArray();
			text = new String(data);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public String filter() {
		return filter(REG);
	}

	@Override
	public String filter(String[] regex) {
		String result = text;
		if (text == null || "".equals(text)) {
			return null;
		}
		
		for (String reg : regex) {
			result = result.replaceAll(reg, "");
		}
		return result;
	}

}